<template>
  <div class="userInfo">
    <van-nav-bar title="个人资料" left-text="返回" right-text="编辑" @click-right="state.show = true" left-arrow
      @click-left="router.back()" :fixed="true" />
    <div class="setList">
      <div class="item">
        <span class="opt">
          头像
        </span>
        <div class="right">
          <img :src="state.avatar" alt="" class="img">
          <svg class="icon iconfont" aria-hidden="true">
            <use xlink:href="#icon-youjiantou"></use>
          </svg>
        </div>

      </div>
      <div class="item">
        <span class="opt">
          性别
        </span>
        <div class="right">
          {{ state.gender }}
          <svg class="icon iconfont" aria-hidden="true">
            <use xlink:href="#icon-youjiantou"></use>
          </svg>
        </div>
      </div>
      <div class="item">
        <span class="opt">
          昵称
        </span>
        <div class="right">
          {{ state.nickname }}
          <svg class="icon iconfont" aria-hidden="true">
            <use xlink:href="#icon-youjiantou"></use>
          </svg>
        </div>
      </div>
      <div class="item">
        <span class="opt">
          简介
        </span>
        <div class="right">
          {{ state.brief_intro }}
          <svg class="icon iconfont" aria-hidden="true">
            <use xlink:href="#icon-youjiantou"></use>
          </svg>
        </div>
      </div>
      <div class="item">
        <span class="opt">
          所在地
        </span>
        <div class="right">
          {{ state.location }}
          <svg class="icon iconfont" aria-hidden="true">
            <use xlink:href="#icon-youjiantou"></use>
          </svg>
        </div>
      </div>

    </div>
    <van-dialog :show="state.show" title="编辑资料" @confirm="editInfo" show-cancel-button @cancel="state.show = false">
      <van-field v-model="state.nickname" name="nickname" label="昵称" placeholder="请输入昵称" maxlength="8" />
      <van-field v-model="state.brief_intro" name="brief_intro" label="简介" placeholder="请输入简介" />
      <van-field name="gender" label="性别">
        <template #input>
          <van-radio-group v-model="state.gender" direction="horizontal">
            <van-radio name="男">男</van-radio>
            <van-radio name="女">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field name="uploader" label="头像">
        <template #input>
          <van-uploader v-model="fileList" :before-read="beforeRead" :max-count="1" />
        </template>
      </van-field>
      <van-field v-model="state.location" is-link readonly name="area" label="地区选择" placeholder="点击选择省市区"
        @click="state.showArea = true" />
      <van-popup v-model:show="state.showArea" position="bottom">
        <van-area :area-list="areaList" @confirm="selectLocation" @cancel="state.showArea = false" />
      </van-popup>
    </van-dialog>
  </div>
</template>

<script setup lang='ts'>
import { useRouter } from 'vue-router';
import { userStore } from '@/store';
import { areaList } from '@vant/area-data';
import { reactive, ref } from 'vue';
import { showFailToast } from 'vant';
import { getToken, setUserInfo} from '@/api/index'
import * as qiniu from 'qiniu-js';
const user = userStore()
const router = useRouter()
let ImgList: Array<string> = [];
const state = reactive({
  show: false,
  showArea: false,
  showCalendar: false,
  hasChange: false,
  avatar: user.userInfo.avatar,
  gender: user.userInfo.gender,
  location: user.userInfo.location,
  nickname: user.userInfo.nickname,
  brief_intro: user.userInfo.brief_intro,
})
const fileList = ref([{
  url: user.userInfo.avatar
}])
const selectLocation = (e: any) => {
  let location: string = ''
  e.selectedOptions.forEach((element: any) => {
    location += element.text
  });
  state.location = location
  state.showArea = false
}

const editInfo = async () => {
  const config = {
    region: qiniu.region.z2,
    domain: 'http://sdcpe1fnv.hd-bkt.clouddn.com'
  }
  if (state.hasChange) {
    await getToken().then((res: any) => {
      fileList.value.forEach((file: any) => {
        const observable = qiniu.upload(file.file, null, res.upToken)
        const observer = {
          complete(res: { hash: string; }) {
            const ImgUrl: string = config.domain + '/' + res.hash;
            ImgList.push(ImgUrl)
          }
        }
        observable.subscribe(observer)
      })
    })
  }
  
  setTimeout(async () => {
    await setUserInfo({
      avatar: ImgList[0],
      gender: state.gender,
      location: state.location,
      nickname: state.nickname,
      brief_intro: state.brief_intro,
      user_id: user.userInfo.user_id
    }).then((res: any) => {
      if (res.code == 200) {
        user.changeUserInfo({
          avatar: ImgList[0],
          gender: state.gender,
          location: state.location,
          nickname: state.nickname,
          brief_intro: state.brief_intro
        })
        state.show = false
      }
    })
  },500)

}

const beforeRead = (file: File | Array<File>) => {
  if (file instanceof Array) {
    file.forEach((item) => {
      checkFile(item)
    })
  } else {
    checkFile(file)
  }
  return true
}
const checkFile = (file: File) => {
  const format = ['png', 'jpg', 'jpeg']
  const index = file.name.lastIndexOf(".");
  const finalName = file.name.substring(index + 1);
  if (!format.includes(finalName.toLowerCase())) {
    showFailToast("请上传" + format.join(",") + "格式图片");
    return false;
  }
  state.hasChange = true
}
</script>

<style lang='less' scoped>
@import url('../common/global.less');

.userInfo {
  background-color: @bg-color;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-bottom: 2rem;
  box-sizing: border-box;
  align-items: center;

  .titleBar {
    height: 3rem;
    background: #fff;
    width: 100%;
    padding: 0 1rem;
    box-sizing: border-box;
    display: grid;
    align-items: center;
    grid-template-columns: 20px auto;

    .iconfont {
      font-size: 1rem;
      grid-column: 1/2;
    }

    .title {
      line-height: 3rem;
      text-align: center;
    }
  }

  .setList {
    width: 100%;
    border-radius: 0.8rem;
    background: #fff;
    display: flex;
    flex-direction: column;
    flex: 1;
    margin-top: 3rem;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 1.5rem;
      cursor: pointer;

      span {
        text-align: center;
        font-weight: 600;
      }

      .right {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 1rem;

        .arrow {
          width: 1rem;
          height: 1rem;
        }
      }

      position: relative;
      height: 3rem;

      .img {
        width: 2rem;
        height: 2rem;
        border-radius: 0.5rem;
      }
    }

    .item::after {
      content: '';
      width: 90%;
      position: absolute;
      height: 1px;
      transform: scale(1, 0.5);
      background: #d7d5d5;
      left: 4%;
      bottom: 0;
    }

  }
}
</style>
